﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Data;
using System.IO;
using System.Text.RegularExpressions;
using System.Web;
using System.Web.Mail;
using System.Web.Services;
using Microsoft.ApplicationBlocks.Data;
using Tiffer;
using Dimok.User;
using Dimok.Data;
/// <summary>
/// Summary description for Imaging
/// </summary>

namespace WS {
	public class Imaging : WebService {
		// Fields
		private UOX uox = new UOX();

		/// <summary>
		/// Converted
		/// </summary>
		[WebMethod]
		public int DeleteApplPage(int applID, int folderID, int startPage, int pageCount) {
			this.uox.applID = applID;
			byte[] image = null;
			if ((startPage == 0) && (pageCount == -1)) {
				this.uox.ImageFolder(folderID, (byte[])null);
			} else {
				image = Tiff.DeletePages(this.uox.ImageFolder(folderID), MakePageNumbers( startPage, pageCount));
				this.uox.ImageFolder(folderID, image);
			}
			return Tiff.PageCount(image);
		}

		/// <summary>
		/// Converted
		/// </summary>
		[WebMethod]
		public int DeleteFile(string fileName, int startPage, int pageCount) {
			if ((startPage != 0) || (pageCount != -1)) {
				return this.DeleteFilePage(fileName, startPage, pageCount);
			}
			File.Delete(this.FilePathFull(fileName));
			return 0;
		}

		/// <summary>
		/// Converted
		/// </summary>
		[WebMethod]
		public int DeleteFilePage(string fileName, int startPage, int pageCount) {
			fileName = this.FilePathFull(fileName);
			Tiff.DeletePages(fileName, MakePageNumbers(startPage, pageCount));
			int num = Tiff.PageCount(fileName);
			if (num == 0) {
				File.Delete(fileName);
			}
			return num;
		}

		private string FilePathFull(string fileName) {
			if (Regex.IsMatch(fileName, Dimok.Config.imaging.WS.ImagePath.Replace(@"\", @"\\")) || Regex.IsMatch(fileName, @"[:]\\")) {
				return fileName;
			}
			return Path.Combine(Dimok.Config.imaging.WS.ImagePath, fileName.Trim() + ".tif");
		}

		private byte[] GetFilePages(string fileName) {
			return this.GetFilePages(fileName, -1, 0);
		}

		/// <summary>
		/// Converted
		/// </summary>
		private byte[] GetFilePages(string fileName, int pageNum, int pageCount) {
			byte[] buffer2;
			try {
				fileName = this.FilePathFull(fileName);
				if ((pageNum == -1) || ((pageNum == 0) && (pageCount == -1))) {
					FileStream stream = new FileStream(fileName, FileMode.Open, FileAccess.Read);
					byte[] buffer = new byte[(uint)stream.Length];
					stream.Read(buffer, 0, buffer.Length);
					stream.Close();
					return buffer;
				}
				buffer2 = Tiff.GetPages(fileName, MakePageNumbers(pageNum, pageCount));
			} catch (Exception exception) {
				throw new Exception("\nFileName:" + fileName + "\nTiffer version:" + Tiff.version, exception);
			}
			return buffer2;
		}

		/// <summary>
		/// Converted
		/// </summary>
		[WebMethod]
		public string GetImageList() {
			return Common.ImageList();
		}

		/// <summary>
		/// Converted
		/// </summary>
		private string GetTempTiffFile() {
			string tempFileName = Path.GetTempFileName();
			string destFileName = tempFileName.Replace(".tmp", ".tif");
			File.Move(tempFileName, destFileName);
			return destFileName;
		}

		/// <summary>
		/// Converted
		/// </summary>
		public void MailFile(string to, string subject, string fileName) {
			MailFile(to, subject, fileName, -1, -1);
		}
		/// <summary>
		/// Converted
		/// </summary>
		[WebMethod]
		public void MailFile(string to, string subject, string fileName, int pageNum, int pageCount) {
			try {
				string path = "";
				fileName = this.FilePathFull(fileName);
				MailMessage message = new MailMessage();
				message.To = to;
				if ((subject != null) && (subject != "")) {
					message.Subject = subject;
				}
				message.From = "\"Imager\" <help@afchome.net>";
				if (pageNum >= 0) {
					byte[] buffer = this.GetFilePages(fileName, pageNum, pageCount);
					path = this.GetTempTiffFile();
					FileStream stream = new FileStream(path, FileMode.Truncate);
					stream.Write(buffer, 0, buffer.Length);
					stream.Close();
					fileName = path;
				}
				message.Attachments.Add(new MailAttachment(fileName));
				SmtpMail.Send(message);
				if (path != "") {
					File.Delete(path);
				}
			} catch (Exception exception) {
				throw new Exception("File:" + fileName + "\n", exception);
			}
		}

		/// <summary>
		/// Converted
		/// </summary>
		[WebMethod]
		public void MailFolder(string to, string subject, int applID, int folderID, int pageNum, int pageCount) {
			this.uox.applID = applID;
			string tempTiffFile = Dimok.FileManager.GetFileFromBytes(this.uox.ImageFolder(folderID), ".tif");
			try {
				this.MailFile(to, subject, tempTiffFile, pageNum, pageCount);
			} finally { File.Delete(tempTiffFile); }
		}

		[WebMethod]
		public int[] MoveFileToFile(string fileFrom, string fileTo, int pageAfter, int pageStart, int pageCount, bool copy) {
			int[] numArray;
			try {
				fileTo = this.FilePathFull(fileTo);
				fileFrom = this.FilePathFull(fileFrom);
				Tiff.AddPages(fileTo, fileFrom, pageAfter, pageStart, pageCount);
				if (!copy) {
					Tiff.DeletePages(fileFrom, pageStart, pageCount);
				}
				int num = Tiff.PageCount(fileFrom);
				if (num == 0) {
					File.Delete(fileFrom);
				}
				numArray = new int[] { num, Tiff.PageCount(fileTo) };
			} catch (Exception exception) {
				throw new ApplicationException("Tiffer:" + Tiff.version + "\n\n", exception);
			}
			return numArray;
		}

		[WebMethod]
		public int[] MoveFileToFolder(int applID, string fileFrom, int startPage, int pageCount, int folderTo, int pageAfter, bool copy) {
			this.uox.applID = applID;
			fileFrom = this.FilePathFull(fileFrom);
			byte[] imgFrom = this.GetFilePages(fileFrom, startPage, pageCount);
			byte[] imgTo = this.uox.ImageFolder(folderTo);
			imgTo = (imgTo.Length == 0) ? this.GetFilePages(fileFrom, startPage, pageCount) :
				Tiff.AddPages(imgTo, Dimok.FileManager.GetBytesFromFile( fileFrom), pageAfter + 1, MakePageNumbers(startPage,pageCount));
			this.uox.ImageFolder(folderTo, imgTo);
			if (!copy) {
				this.DeleteFile(fileFrom, startPage, pageCount);
			}
			return new int[] { this.PageCount(fileFrom), Tiff.PageCount(imgTo) };
		}

		[WebMethod]
		public int[] MoveFolderToFile(int applID, int folderID, string fileName, int pageAfter, int pageStart, int pageCount, bool copy) {
			this.uox.applID = applID;
			fileName = this.FilePathFull(fileName);
			byte[] imageFrom = this.uox.ImageFolder(folderID);
			Tiff.AddPages(fileName, imageFrom, pageAfter, pageStart, pageCount);
			if (!copy) {
				imageFrom = Tiff.DeletePages(imageFrom, pageStart, pageCount);
				this.uox.ImageFolder(folderID, imageFrom);
			}
			return new int[] { Tiff.PageCount(imageFrom), Tiff.PageCount(fileName) };
		}

		[WebMethod(EnableSession = true)]
		public int[] MoveFolderToFolder(int applID, int folderTo, int folderFrom, int pageAfter, int pageStart, int pageCount, bool copy) {
			this.uox.applID = applID;
			byte[] imgTo = this.uox.ImageFolder(folderTo);
			byte[] image = this.uox.ImageFolder(folderFrom);
			if (image.Length != 0) {
				if (imgTo.Length == 0) {
					imgTo = Tiff.GetPages(image,MakePageNumbers(pageStart, pageCount));
				} else {
					imgTo = Tiff.AddPages(imgTo, image, pageAfter,MakePageNumbers(pageStart, pageCount));
				}
				this.uox.ImageFolder(folderTo, imgTo);
				if (!copy) {
					image = Tiff.DeletePages(image, pageStart, pageCount);
					this.uox.ImageFolder(folderFrom, image);
				}
			}
			return new int[] { Tiff.PageCount(image), Tiff.PageCount(imgTo) };
		}

		[WebMethod]
		public void MoveWithinFile(string fileName, int pageAfter, int pageStart, int pageCount) {
			byte[] buffer = Tiff.MovePages(this.GetFilePages(fileName), pageAfter, pageStart, pageCount);
			FileStream stream = new FileStream(this.FilePathFull(fileName), FileMode.Truncate, FileAccess.Write);
			stream.Write(buffer, 0, buffer.Length);
			stream.Close();
		}

		[WebMethod]
		public void MoveWithinFolder(int applID, int folderID, int pageAfter, int pageStart, int pageCount) {
			this.uox.applID = applID;
			byte[] image = Tiff.MovePages(this.uox.ImageFolder(folderID), pageAfter, pageStart, pageCount);
			this.uox.ImageFolder(folderID, image);
		}

		[WebMethod]
		public int NewFileFromFile(string newFile, string fileName, int pageNum, int pageCount, bool copy) {
			newFile = this.FilePathFull(newFile);
			fileName = this.FilePathFull(fileName);
			if (((pageNum == 0) && (pageCount == -1)) && !copy) {
				File.Move(fileName, newFile);
				return 0;
			}
			if (File.Exists(newFile)) {
				throw new ApplicationException("File " + newFile + " allready exists.");
			}
			byte[] buffer = Tiff.GetPages(fileName, MakePageNumbers(pageNum, pageCount));
			FileStream stream = new FileStream(newFile, FileMode.Create);
			stream.Write(buffer, 0, buffer.Length);
			stream.Close();
			if (!copy) {
				return this.DeleteFilePage(fileName, pageNum, pageCount);
			}
			return Tiff.PageCount(fileName);
		}

		[WebMethod]
		public int NewFileFromFolder(int applID, string newFile, int folderID, int pageNum, int pageCount, bool copy) {
			this.uox.applID = applID;
			newFile = this.FilePathFull(newFile);
			if (File.Exists(newFile)) {
				throw new ApplicationException("File " + newFile + " allready exists.");
			}
			byte[] image = this.uox.ImageFolder(folderID);
			if (image.Length == 0) {
				throw new ApplicationException("\n\nCan't create file from empty folder.\n\n");
			}
			FileStream stream = new FileStream(newFile, FileMode.Create);
			byte[] buffer = Tiff.GetPages(image, pageNum, pageCount);
			stream.Write(buffer, 0, buffer.Length);
			stream.Close();
			if (!copy) {
				this.uox.ImageFolder(folderID, image = Tiff.DeletePages(image, pageNum, pageCount));
			}
			return Tiff.PageCount(image);
		}

		[WebMethod]
		public int PageCount(string fileName) {
			int num;
			try {
				fileName = this.FilePathFull(fileName);
				if (!File.Exists(fileName)) {
					return 0;
				}
				num = Tiff.PageCount(fileName);
			} catch (Exception exception) {
				throw new Exception("\nFileName:" + fileName + "\nTiffer version:" + Tiff.version, exception);
			}
			return num;
		}

		[WebMethod]
		public int PageCount_Appl(int applID, int folderID) {
			return Tiff.PageCount(this.uox.ImageFolder(applID, folderID));
		}

		[WebMethod]
		public void ShowApplPages(int applID, int folderID, int pageNum, int pageCount) {
			try {
				this.uox.applID = applID;
				byte[] buffer = this.uox.ImageFolder(folderID);
				if ((buffer != null) && (buffer.Length != 0)) {
					buffer = Dimok.ABCPdf.TiffToPDF(Tiff.GetPages(buffer, MakePageNumbers(pageNum, pageCount)));
					Context.Response.ContentType = Dimok.Images.Enums.GetContentType(buffer);
					Context.Response.BinaryWrite(buffer);
				} else {
					Context.Response.Write("<pre>No images in \"" + SqlHelper.ExecuteScalar(this.uox.db, CommandType.Text, "SELECT ImageType FROM t_ImageType WHERE ID=" + folderID) + "\".</pre>");
				}
			} catch (Exception exception) {
				Context.Response.ContentType = "text/html";
				throw new Exception("\nTiffer version:" + Tiff.version, exception);
			}
		}
		private int[] MakePageNumbers(int PageNumber, int PageCount) {
			if (PageNumber >= 0 && PageCount > 0) PageNumber++;
			if (PageNumber == 0 && PageCount < 0) PageNumber--;
			List<int> pageNumbers = new List<int>();
			do {
				pageNumbers.Add(PageNumber++);
			} while (--PageCount > 0);
			return pageNumbers.ToArray();
		}

		[WebMethod]
		public void ShowFilePages(string fileName, int pageNum, int pageCount) {
			try {
				byte[] file = Dimok.ABCPdf.TiffToPDF(this.GetFilePages(fileName, pageNum, pageCount));
				Context.Response.ContentType = Dimok.Images.Enums.GetContentType(file);
				Context.Response.BinaryWrite(file);
			} catch (Exception exception) {
				throw new Exception("\nFileName:" + fileName + "\nTiffer version:" + Tiff.version, exception);
			}
		}
	}


}